import React, { useState, useEffect, useCallback, useMemo } from 'react'
import styles from './index.module.less'
import classNames from 'classnames'

const EatRandom = () => {
	const [start, setStart] = useState(false)
	const [current, setCurrent] = useState(1)
	const [timer, setTimer] = useState(null)
	const [time, setTime] = useState(200)

	const list = [
		{ label: 1 },
		{ label: 2 },
		{ label: 3 },
		{ label: 8 },
		{ label: '抽' },
		{ label: 4 },
		{ label: 7 },
		{ label: 6 },
		{ label: 5 },
	]

	// 触发抽奖
	const click = useCallback(() => {
		if (timer || start) {
			return
		}
		setStart((f) => !f)
	}, [timer, start])

	// 清除定时器
	const clearTimer = useCallback(() => {
		if (timer) {
			setTimeout(() => {
				setTimer(null)
				clearInterval(timer)
			}, 0)
		}
	}, [timer])

	// 监听状态 start: true 开始抽奖
	useMemo(() => {
		if (start) {
			setTimer(() => {
				return setInterval(() => {
					setCurrent((num) => {
						if (num + 1 === 8) {
							setTime((t) => t - 50)
						}
						return num + 1 > 8 ? 1 : num + 1
					})
				}, time)
			})
		}
	}, [start])

	useMemo(() => {
		;(async () => {
			await clearTimer()
			console.log(2222)
			if (start) {
				setTimer(() => {
					return setInterval(() => {
						setCurrent((num) => {
							if (num + 1 === 8) {
								setTime((t) => t - 50)
							}
							return num + 1 > 8 ? 1 : num + 1
						})
					}, time)
				})
			}
		})()
	}, [time])

	// 监听定时器  定时器开始 几秒后关闭
	useMemo(() => {
		if (timer) {
			setTimeout(() => {
				clearTimer()
				setStart(false)
			}, 2000)
		}
	}, [timer])

	return (
		<div className={styles.box}>
			{list.map((item, index) => {
				return (
					<div
						key={index}
						className={classNames(styles.item, current === item.label && styles.activeItem)}
						onClick={() => {
							index === 4 && click()
						}}
					>
						{item.label}
					</div>
				)
			})}
		</div>
	)
}

export default EatRandom
